//
//  DownLoad.m
//  视频播放
//
//  Created by 0.0 on 15-4-13.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//

#import "DownLoad.h"
#import "MD5.h"
#import "DownLoadDataBase.h"
#import "DownLoadModel.h"

@interface DownLoad ()
{
    UIAlertView *_downAlertView; // 下载提示view
    UIAlertView *_downOkAlertView; // 已经下载提示view
    NSTimer *_timer; // 计时器
    
}
@property (nonatomic, retain) NSString *aFileName;
@end

@implementation DownLoad

- (void)dealloc
{
    [_aFileName release];
    
    [super dealloc];
}

/**
 * 下载文件
 */
- (void)downloadFileURL:(NSArray *)aUrl savePath:(NSString *)aSavePath num:(NSInteger)num imageURL:(NSString *)imageURL vegetableName:(NSString *)vegetableName
{
    // 存储下载状态的文件
    NSString *statePath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
    statePath = [NSString stringWithFormat:@"%@/%@", statePath, vegetableName];
    
    // 判断当前是否正在下载状态
   
    
    CGFloat loadStateNum = 0.0f;
    NSInteger arrayCount = [aUrl count];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    // 如果视频全部下载完成走这个if方法
    if (num >= arrayCount) {
        
     
        [self release];
        return;
    }
    
    // 获取网址(视频下载完成退出这个方法)
    NSString *URL = [aUrl objectAtIndex:num];
    
    // 获取以网址最后斜杠后面的字符串为mp4文件名
    self.aFileName = [MD5 getVideoNameWithURL:URL];
    
    //检查本地文件是否已存在
    NSString *fileName = [NSString stringWithFormat:@"%@/%@", aSavePath, _aFileName];
    
    // 将2个视频的网址拼接成字符串存到数据库中
    NSString *videoURLPath = nil;
    for (NSString *url in aUrl) {
        if (videoURLPath == nil) {
            videoURLPath = [NSString stringWithFormat:@"%@", url];
        }
        else {
            videoURLPath = [NSString stringWithFormat:@"%@$%@", videoURLPath, url];
        }
    }
    
    // 检查文件是否存在
    if (![fileManager fileExistsAtPath:fileName]) {
        
        // 检查video文件夹是否存在不存在则创建一个
        if (![fileManager fileExistsAtPath:aSavePath]) {
            [fileManager createDirectoryAtPath:aSavePath withIntermediateDirectories:YES attributes:nil error:nil];
        }
        
        // 只提示一次正在下载中
        if (0 == num) {
            // 提示视频正在下载
            _downAlertView = [[UIAlertView alloc] initWithTitle:@"正在下载" message:@"稍后可到,我的->视频列表查看" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
            [_downAlertView show];
            _timer = [NSTimer scheduledTimerWithTimeInterval:3.0f target:self selector:@selector(downAction) userInfo:nil repeats:YES];
            
            // 将视频名字, 路径, 和图片路径存入数据库
            DownLoadModel *model = [[DownLoadModel alloc] initWithVideoName:_aFileName videoPath:videoURLPath videoImage:imageURL vegetable:vegetableName stateNum:0.0];
            [DownLoadDataBase insertWithModel:model];
        }
       
        // 下载附件
        NSURL *url = [[[NSURL alloc] initWithString:URL] autorelease];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        
        AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc] initWithRequest:request] autorelease];
        operation.inputStream   = [NSInputStream inputStreamWithURL:url];
        operation.outputStream  = [NSOutputStream outputStreamToFileAtPath:fileName append:NO];
        [operation start];
        
        // 下载进度控制
        __block CGFloat getNum = loadStateNum;
//        __block NSInteger arrayCount2 = arrayCount;
        __block DownLoad *movie = self;
        __block NSInteger b = num;
//        __block NSMutableDictionary *bic = dic;
//        __block DownLoadDataBase *down = [DownLoadDataBase downLoadDataBase];
        [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
            getNum = (float)totalBytesRead / totalBytesExpectedToRead;
            getNum = b + getNum;
//            [DownLoadDataBase updateWithStateNum:getNum / arrayCount videoName:vegetableName];//  因为视频名字会变, 这里我们用网址来寻找字段刷新state值

            NSString *state = [NSString stringWithFormat:@"%f", getNum / arrayCount];
            [state writeToFile:statePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
            
             NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"1", @"key", nil];
//            [dic setObject:@"1" forKey:@"key"];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"changeNum" object:nil userInfo:dic];
            // 当前视频下载完成时候调用下面if中方法
            if (getNum == 1) {
                b++;
                // 当下载完成以后, 递归调用本方法执行下一个下载
                [movie downloadFileURL:aUrl savePath:aSavePath num:b imageURL:imageURL vegetableName:vegetableName];
            }
            NSLog(@"...%f", getNum);
        }];
        
    }
    // 如果已经下载过则不进行下载提示信息
    else {
        _downOkAlertView = [[UIAlertView alloc] initWithTitle:@"提示消息" message:@"已下载" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [_downOkAlertView show];
        _timer = [NSTimer scheduledTimerWithTimeInterval:2.0f target:self selector:@selector(downOkAction) userInfo:nil repeats:YES];
    }
    NSLog(@"%@", fileName);
    
}

- (void)downOkAction
{
    [_timer invalidate];
    [_downOkAlertView dismissWithClickedButtonIndex:0 animated:YES];
    [_downOkAlertView release];
    
}

- (void)downAction
{
    [_timer invalidate];
    [_downAlertView dismissWithClickedButtonIndex:0 animated:YES];
    [_downAlertView release];
}

@end
